//cmdline
#include "../cmdline.h"
using namespace dzlua;

//libevent
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#ifndef WIN32
#include <netinet/in.h>
# ifdef _XOPEN_SOURCE_EXTENDED
#  include <arpa/inet.h>
# endif
#include <sys/socket.h>
#endif

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>

//self
#include <iostream>
#include <string>
using namespace std;

struct sCmdInfo {
    std::string host;
    std::string cmd;
    int port;
};

bool SendCmd(sCmdInfo& cmd) {
    cout << "cmd: " << cmd.cmd << endl;
    WORD wVersion;
	WSADATA wsaData;
	wVersion = MAKEWORD(1, 1);
	int err = WSAStartup(wVersion, &wsaData);
	if (0 != err)
		return false;

	if (wsaData.wVersion != wVersion) {
		WSACleanup();
		return false;
	}

    SOCKADDR_IN addrSrv;  
    addrSrv.sin_family = AF_INET;  
    addrSrv.sin_port = htons(cmd.port);  
    addrSrv.sin_addr.S_un.S_addr = inet_addr(cmd.host.c_str());

    SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
    if (SOCKET_ERROR == sockClient) {
        printf("Socket() error:%d", WSAGetLastError());
        return false;
    }

    if (connect(sockClient, (struct sockaddr*)&addrSrv, sizeof(addrSrv)) == INVALID_SOCKET) { 
        printf("Connect failed:%d", WSAGetLastError());
        return false;
    }

    char buff[1024];
    recv(sockClient, buff, sizeof(buff), 0);
    printf("%s\n", buff);

    send(sockClient, cmd.cmd.c_str(), cmd.cmd.length(), 0);

    ::ZeroMemory (buff, sizeof(buff));
    recv(sockClient, buff, sizeof(buff), 0);
    printf("%s\n", buff);

    closesocket(sockClient);
    WSACleanup();

    return true;
}

int main(int argc, char** argv) {
    cmdline::parser cmdl;
    cmdl.add<std::string>("host", 'h', "host name", false, "127.0.0.1");
    cmdl.add<int>("port", 'p', "port number", false, 25092, cmdline::range(1, 65535));
    cmdl.add<std::string>("type", 't', "protocol type", false, "http", cmdline::oneof<std::string>("http", "https", "ssh", "ftp"));
    cmdl.add<std::string>("command", 'c', "the comman send to server");

    cmdl.set_program_name("client");
    cmdl.parse_check(argc, argv);

    if (argc == 1 || cmdl.exist("help")){
        cerr << cmdl.usage();
        return 0;
    }

    if (cmdl.exist("command")) {
        sCmdInfo info;
        info.host = cmdl.get<std::string>("host");
        info.port = cmdl.get<int>("port");
        info.cmd = cmdl.get<std::string>("command");
        if (!SendCmd(info)) {
            cerr << "Error: not send to server!" << endl;
        }
        return 0;
    }

    return 0;
}